<template>
  <div class="merchant-add-goods">
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>添加新商品</span>
          <el-button type="primary" @click="submitForm" :loading="loading">发布商品</el-button>
        </div>
      </template>

      <el-form 
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="goods-form"
      >
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入商品名称" maxlength="100" show-word-limit />
        </el-form-item>

        <el-form-item label="商品分类" prop="categoryId">
          <el-cascader
            v-model="formData.categoryId"
            :options="categoryOptions"
            :props="{ checkStrictly: true }"
            placeholder="请选择商品分类"
            clearable
          />
        </el-form-item>

        <el-form-item label="商品主图" prop="mainImage">
          <el-upload
            class="main-image-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleMainImageSuccess"
            :before-upload="beforeImageUpload"
          >
            <img v-if="formData.mainImage" :src="formData.mainImage" class="main-image" />
            <el-icon v-else class="main-image-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸：800x800px，支持jpg、png格式</div>
        </el-form-item>

        <el-form-item label="商品图片" prop="images">
          <el-upload
            :action="uploadUrl"
            :headers="uploadHeaders"
            list-type="picture-card"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            :on-remove="handleImageRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">最多上传9张图片，建议尺寸：800x800px</div>
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input-number 
            v-model="formData.price" 
            :precision="2" 
            :step="0.1" 
            :min="0"
            placeholder="请输入商品价格"
          />
        </el-form-item>

        <el-form-item label="商品库存" prop="stock">
          <el-input-number 
            v-model="formData.stock" 
            :min="0" 
            :precision="0"
            placeholder="请输入商品库存"
          />
        </el-form-item>

        <!-- 商品规格 -->
        <el-divider content-position="left">商品规格</el-divider>
        <el-form-item label="规格类型">
          <el-radio-group v-model="specType">
            <el-radio :value="0">单规格</el-radio>
            <el-radio :value="1">多规格</el-radio>
          </el-radio-group>
        </el-form-item>

        <template v-if="specType === 1">
          <el-form-item label="规格名称">
            <el-input 
              v-model="specName" 
              placeholder="请输入规格名称，如：颜色、尺寸"
              style="width: 200px"
            />
            <el-button type="primary" link @click="addSpecName">添加规格</el-button>
          </el-form-item>

          <el-form-item label="规格值">
            <div v-for="(spec, index) in formData.specs" :key="index" class="spec-item">
              <span class="spec-name">{{ spec.name }}：</span>
              <el-tag
                v-for="(value, vIndex) in spec.values"
                :key="vIndex"
                closable
                @close="removeSpecValue(index, vIndex)"
                class="spec-value"
              >
                {{ value }}
              </el-tag>
              <el-input
                v-if="spec.inputVisible"
                ref="specInputRef"
                v-model="spec.inputValue"
                class="spec-input"
                size="small"
                @keyup.enter="addSpecValue(index)"
                @blur="addSpecValue(index)"
              />
              <el-button v-else type="primary" link @click="showSpecInput(index)">
                添加规格值
              </el-button>
            </div>
          </el-form-item>

          <el-form-item label="规格组合">
            <el-table :data="specCombinations" border style="width: 100%">
              <el-table-column label="规格" min-width="200">
                <template #default="scope">
                  {{ scope.row.specText }}
                </template>
              </el-table-column>
              <el-table-column label="价格" width="200">
                <template #default="scope">
                  <el-input-number 
                    v-model="scope.row.price" 
                    :precision="2" 
                    :step="0.1" 
                    :min="0"
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column label="库存" width="200">
                <template #default="scope">
                  <el-input-number 
                    v-model="scope.row.stock" 
                    :min="0" 
                    :precision="0"
                    size="small"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </template>

        <!-- 商品详情 -->
        <el-divider content-position="left">商品详情</el-divider>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="商品详情" prop="detail">
          <el-upload
            :action="uploadUrl"
            :headers="uploadHeaders"
            list-type="picture-card"
            :on-success="handleDetailImageSuccess"
            :before-upload="beforeImageUpload"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">支持jpg、png格式，建议宽度750px</div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import service from '@/utils/request'

const router = useRouter()
const formRef = ref(null)
const loading = ref(false)
const specType = ref(0)
const specName = ref('')
const specInputRef = ref(null)

// 上传相关
const uploadUrl = import.meta.env.VITE_API_URL + '/upload'
const uploadHeaders = {
  token: localStorage.getItem('token')
}

// 表单数据
const formData = reactive({
  title: '',
  categoryId: null,
  mainImage: '',
  images: [],
  price: 0,
  stock: 0,
  specs: [],
  description: '',
  detail: []
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  mainImage: [
    { required: true, message: '请上传商品主图', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' }
  ]
}

// 分类选项
const categoryOptions = ref([])

// 获取分类数据
const getCategories = async () => {
  try {
    const res = await service.get('/categories')
    categoryOptions.value = res
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 图片上传相关方法
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleMainImageSuccess = (res) => {
  formData.mainImage = res.url
}

const handleImageSuccess = (res) => {
  formData.images.push(res.url)
}

const handleImageRemove = (file) => {
  const index = formData.images.indexOf(file.url)
  if (index !== -1) {
    formData.images.splice(index, 1)
  }
}

const handleDetailImageSuccess = (res) => {
  formData.detail.push(res.url)
}

// 规格相关方法
const addSpecName = () => {
  if (!specName.value) {
    ElMessage.warning('请输入规格名称')
    return
  }
  formData.specs.push({
    name: specName.value,
    values: [],
    inputVisible: false,
    inputValue: ''
  })
  specName.value = ''
}

const showSpecInput = (index) => {
  formData.specs[index].inputVisible = true
  setTimeout(() => {
    specInputRef.value.focus()
  })
}

const addSpecValue = (index) => {
  const spec = formData.specs[index]
  if (spec.inputValue) {
    spec.values.push(spec.inputValue)
  }
  spec.inputVisible = false
  spec.inputValue = ''
}

const removeSpecValue = (specIndex, valueIndex) => {
  formData.specs[specIndex].values.splice(valueIndex, 1)
}

// 计算规格组合
const specCombinations = computed(() => {
  if (specType.value === 0) return []
  
  const specs = formData.specs
  if (specs.length === 0) return []

  const combinations = []
  const generateCombinations = (current, index) => {
    if (index === specs.length) {
      combinations.push({
        specText: current.map(item => `${item.name}:${item.value}`).join('、'),
        price: formData.price,
        stock: formData.stock
      })
      return
    }

    const spec = specs[index]
    spec.values.forEach(value => {
      generateCombinations([...current, { name: spec.name, value }], index + 1)
    })
  }

  generateCombinations([], 0)
  return combinations
})

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const submitData = {
      ...formData,
      specType: specType.value,
      specCombinations: specType.value === 1 ? specCombinations.value : []
    }

    await service.post('/merchant/goodss', submitData)
    ElMessage.success('商品发布成功')
    router.push('/merchant/goodss')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败，请检查表单')
  } finally {
    loading.value = false
  }
}

// 初始化
getCategories()
</script>

<style scoped>
.merchant-add-goods {
  padding: 20px;
}

.form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-form {
  max-width: 1000px;
  margin: 0 auto;
}

.main-image-uploader {
  width: 200px;
  height: 200px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.main-image-uploader:hover {
  border-color: var(--el-color-primary);
}

.main-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 200px;
  text-align: center;
  line-height: 200px;
}

.main-image {
  width: 200px;
  height: 200px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.spec-item {
  margin-bottom: 10px;
}

.spec-name {
  font-weight: bold;
  margin-right: 10px;
}

.spec-value {
  margin-right: 10px;
  margin-bottom: 5px;
}

.spec-input {
  width: 100px;
  margin-right: 10px;
  vertical-align: bottom;
}
</style> 